package com.example.demo.service;

import com.alibaba.fastjson.JSONObject;
import com.ffcs.oss.files.server.controller.FileJDK;
import com.ffcs.oss.files.server.controller.FileResult;
import com.example.demo.mapper.FileMapper;
import com.ffcs.oss.param.out.ServiceResp;
import com.example.demo.security.SecurityUtils;
import com.example.demo.web.rest.evt.attachment.FileInfoEvt;
import com.example.demo.web.rest.evt.attachment.ObjEvt;
import com.example.demo.web.rest.vm.attachment.FileInfoVm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @Desc
 * @Author zhengmf
 * @Date 2019-06-28 11:06:06
 */
@Service
public class FileService {
    @Autowired
    private FileMapper fileMapper;

    /**
     * 获取上传文件服务器地址
     * @param key
     * @return
     */
    public String getFileServerUrl(String key) {
        return fileMapper.getFileServerUrl(key);
    }

    /**
     * 保存上传附件信息
     * @param evt
     */
    public void saveFileInfo(FileInfoEvt evt) {
        //修改的时候
        String oldFileIds = evt.getOldFileIds();
        if (StringUtils.isNotBlank(oldFileIds)) {
            fileMapper.updateFileStatus(Arrays.asList(oldFileIds.split(",")));
        }
        //保存文件相关信息入库
        List<Map<String, Object>> fileResultMap = evt.getFileResult().getResult();
        for (Map<String, Object> resultMap : fileResultMap) {
            String fileName = String.valueOf(resultMap.get("fileName"));
            FileInfoVm fileEvt = new FileInfoVm(String.valueOf(resultMap.get("fileId")), fileName,
                String.valueOf(resultMap.get("filePath")), evt.getObjId(), evt.getObjType());
            Object obj = resultMap.get("fileSize");
            fileEvt.setFileSize(obj==null?null:Long.parseLong(obj.toString()));
            fileMapper.insertFileUploadTbl(fileEvt);
        }
    }

    /**
     * 获取对象的附件列表信息
     * @param evt
     * @return
     */
    public List<FileInfoVm> getFileByObj(ObjEvt evt) {
        return fileMapper.getFileByObj(evt);
    }

    /**
     * 附件下载
     * @param response
     * @param fileId
     * @return
     * @throws IOException
     */
    public ServiceResp downloadFile(HttpServletResponse response, String fileId) {
        try{
           // String agent = request.getHeader("User-Agent").toLowerCase();
            Map<String, Object> params = new HashMap<>();
            FileInfoVm fileUpload = fileMapper.getFileByFileId(fileId);
            params.put("key", "ocIuf+maLnM=");
            params.put("path", fileUpload.getFilePath());
            params.put("id", fileId);
            OutputStream os = new BufferedOutputStream(response.getOutputStream());
            //访问文件服务路径
            String downloadUrl = fileMapper.getFileServerUrl("FILE_DOWNLOAD_URL");
            String rel = FileJDK.download(downloadUrl, params);
            FileResult fileResult = JSONObject.parseObject(rel, FileResult.class);
            InputStream fis = new ByteArrayInputStream(fileResult.getObjectMetadata());
            int b;
            byte[] buffer = new byte[1024];
            while ((b = fis.read(buffer)) != -1) {
                os.write(buffer, 0, b);
            }
            os.flush();
            os.close();
        }catch (Exception e){
            e.printStackTrace();
            return ServiceResp.getInstance().error(e.getMessage());
        }
        return ServiceResp.getInstance().success("下载成功！");
    }

    private OutputStream setResponseHead(HttpServletResponse response, String filename,
                                         String agent) throws IOException {
        response.reset();
        if (agent.indexOf("msie 8") > 0) {
            // 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode(filename.trim(), "UTF8"));
        } else {
            response.addHeader("Content-Disposition", "attachment;filename="
                + new String(filename.trim().getBytes(StandardCharsets.UTF_8), "iso8859-1"));
        }
        return new BufferedOutputStream(response.getOutputStream());
    }

    public List<Map<String,Object>> uploadFile(MultipartHttpServletRequest multipartRequest, FileInfoEvt fileEvt){
        //        图片上传
        List<MultipartFile> multipartFileList = multipartRequest.getFiles("file");
        if (multipartFileList.size()>0) {
            String path = getFileServerUrl("FILE_UPLOAD_URL");
            Map<String, Object> params = new HashMap<>();
            params.put("multiRequest", multipartRequest);
            params.put("key", "ocIuf+maLnM=");
            params.put("fileStaff", SecurityUtils.getCurrentUserLogin().get());
            String rel = FileJDK.upFileMulti(path, params);
            FileResult fileResult = JSONObject.parseObject(rel, FileResult.class);
            if (fileResult == null) {
                throw new RuntimeException("文件上传返回null,上传失败！");
            }
          /*  for (Map<String, Object> m : fileResult.getResult()) {
                for (MultipartFile file : multipartFileList) {
                    if (String.valueOf(m.get("fileName")).equals(file.getOriginalFilename())) {
                        m.put("fileSize", file.getSize());
                        break;
                    }
                }
            }*/
            fileEvt.setFileResult(fileResult);
            saveFileInfo(fileEvt);
            return fileResult.getResult();
        }
        return Collections.emptyList();
    }

    /**
     * 删除附件
     * @param delFileIds
     */
   public void delFile(String delFileIds){
       fileMapper.updateFileStatus(Arrays.asList(delFileIds.split(",")));
   }

    /**
     * 根据文件ID获取文件路径
     * @param fileId
     * @return
     */
    public FileInfoVm getFileByFileId(String fileId){
        return fileMapper.getFileByFileId(fileId);
    }

}
